<template>
    <Tabs type="card">
        <TabPane label="电表充值">
            <Card class="no-border-card">
                <p slot="title">
                    电表充值
                    <Button type="primary" class="btn-in-top-large" @click="handleExport">导出报表</Button>
                </p>

                <Row :gutter="20" style="margin-bottom:15px">
                    <i-col span="6">
                        <Select placeholder="充值渠道" v-model="search.charge_channel" clearable>
                            <Option v-for="channel in chargeChannels" :key="channel.id" :value="channel.id">
                                {{channel.label}}
                            </Option>
                        </Select>
                    </i-col>
                    <i-col span="6">
                        <city-selector v-model="search.region_code" :placeholder="'请选择所在城市'"></city-selector>
                    </i-col>
                    <i-col span="6">
                        <DatePicker
                            v-model="search.date"
                            type="daterange"
                            :clearable="false"
                            :options="dateOptions"
                            class="width-100p"
                        />
                    </i-col>
                    <i-col span="6">
                        <i-input
                            v-model.trim="search.keyword"
                            placeholder="房源编号/房源地址"
                            icon="ios-search-strong"
                            @on-enter="handleSearch"
                            @on-click="handleSearch">
                        </i-input>
                    </i-col>
                </Row>

                <Table
                    border
                    size="small"
                    class="min-width-table"
                    :columns="columns"
                    :data="tableData"
                    :loading="loading"
                />

                <div class="text-center">
                    <Page
                        show-total
                        :total="pagination.total"
                        :page-size="pagination.limit"
                        :current.sync="pagination.current"
                        @on-change="initData"
                    />
                </div>
            </Card>
        </TabPane>
    </Tabs>

</template>

<script>
    import debounce from 'lodash/debounce'
import pickBy from 'lodash/pickBy'
import { chargeChannel } from '@/libs/const'
import { http, api } from '@/libs/http'
import citySelector from '@/components/city-code-selector'
import { date as format, monthAgo, now, shortcuts, searchTimeRange } from '@/libs/date'

export default {
      name: 'report-electric-charge',
      components: {
        citySelector
      },
      data () {
        return {
          loading: false,
          search: {
            charge_channel: '',
            region_code: '',
            keyword: '',
            date: [monthAgo, now]
          },
          dateOptions: { shortcuts },
          chargeChannels: chargeChannel.list,
          pagination: {
            total: 0,
            current: 1,
            limit: 20
          },
          tableData: [],
          columns: [
            { title: '充值渠道', key: 'chargeType' },
            { title: '所在地区', key: 'area' },
            { title: '房源编号', key: 'home_name' },
            { title: '房源地址', key: 'address' },
            { title: '房间', key: 'room_name' },
            { title: '充值人', key: 'chargetClient' },
            { title: '金额（元）', key: 'chargeAmount' },
            { title: '电价（元/度）', key: 'chargeElePrice' },
            { title: '购电量（度）', key: 'chargePower' },
            // { title: '公摊扣减(度)', key: 'amount' },
            // { title: '电表入电(度)', key: 'charge_pool_amount' },
            { title: '充值时间', key: 'chargeTime' }
          ]
        }
      },
      created () {
        this.initData()
      },
      methods: {
        getQuery (isExport = false) {
          const { charge_channel, region_code, date, keyword } = this.search
          const { current, limit } = this.pagination
          const [ start_time, end_time ] = searchTimeRange(date)
          const query = pickBy({
            charge_channel, region_code, start_time, end_time, keyword
          }, val => !!val)
          if (isExport) {
            return { ...query, download: true }
          }
          return { ...query, limit, offset: (current - 1) * limit }
        },
        handleSearch: debounce(function () {
          this.pagination.current = 1
          this.initData()
        }, 250),
        async initData () {
          try {
            this.loading = true
            const query = this.getQuery()
            const res = await http.req(api.elemeter_charge_report, null, query)
            if (res) {
              this.pagination.total = res.count
              this.tableData = this.formatData(res.rows)
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },
        handleExport () {
          const query = this.getQuery(true)
          http.exportTable(this, api.elemeter_charge_report, null, query)
        },
        getchargeStatus (status) {
          return ['充值中', '充值失败', '充值成功'][status - 1]
        },
        formatData (list) {
          return list.map(item => {
            const {
              charge_name, ele_price, fees, charge_channel, charge_status, room_name,
              amount, charge_pool_amount, charge_time, home: { address, district, city, home_name } = {}
            } = item
            const elePrice = Number(ele_price) || 0
            const result = {
              chargeElePrice: elePrice.toFixed(4),
              chargeAmount: Number(fees) / 100
            }

            if (ele_price === null) {
              result.chargeElePrice = '-'
              result.chargeAmount = '-'
            }
            result.chargePower = (Number(amount) + Number(charge_pool_amount)).toFixed(2)
            const channelDetail = this.chargeChannels.find(item => item.id === charge_channel) || { label: '-', user: '-' }
            return {
              ...result,
              amount,
              address,
              home_name,
              room_name,
              charge_pool_amount,
              area: city + district,
              chargetClient: channelDetail.user + (channelDetail.noName ? '' : charge_name),
              chargeType: channelDetail.label,
              chargeTime: format(charge_time, 'YYYY-MM-DD HH:mm'),
              chargeStatus: this.getchargeStatus(charge_status)
            }
          })
        }
      }
    }
</script>

<style lang="less">
.export-link {
    color: #fff;
    text-decoration: none;
}
.export-link:hover {
    color: #fff;
}
</style>